package eth_manager

import (
	"errors"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center-client/util"
	"net"
	"strings"
)

const (
	eth0     = "eth0"
	wifi     = "wifi"
	enp4s0f2 = "enp4s0f2"
	wlp3s0   = "wlp3s0"
)

var (
	nets = util.NewSet()
)

func init() {
	nets.AddAll(eth0, wifi, enp4s0f2, wlp3s0)
}

func GetListenEth() (string, error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		logger.Errorf("Get eth fail, err is %v", err)
		return "", errors.New("get eth fail")
	}
	for _, eth := range interfaces {
		if !nets.Contains(eth.Name) {
			continue
		}
		if eth.Flags&net.FlagUp == 0 {
			continue
		}
		addrArr, err := eth.Addrs()
		if err != nil {
			logger.Warn("listen eth err, err is %v", err)
			continue
		}
		for _, a := range addrArr {
			ipTep := getIp(a.String())
			if ipTep == "" {
				continue
			}
			ip := net.ParseIP(ipTep)
			if ip == nil {
				logger.Warn("listen ip err, ip is nil")
				continue
			}
			ipv4 := ip.To4()
			if ipv4 == nil {
				continue
			}
			return ipv4.String(), nil
		}
	}
	return "", errors.New("current node eth not ip")
}

func getIp(ip string) string {
	index := strings.Index(ip, "/")
	if index == -1 {
		return ip
	}
	return ip[:index]
}
